
<template>
  <div class="app-container edit-box">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="课程相册" prop="introducePictures">
        <el-row type="flex">
          <draggable
            style="display:flex"
            v-model="ruleForm.introducePictures"
            :options="{animation:500}"
          >
            <div v-for="(item,index) in ruleForm.introducePictures" :key="index" class="img-upload">
              <el-image fit="contain" :src="item" />
              <div class="img-upload-shaow">
                <i class="el-icon-delete" @click="removeImg(index)" />
              </div>
            </div>
            <!-- <div v-show="disabled" class="img-upload" @click="handleUpload">
              <i class="el-icon-plus" />
            </div>-->
          </draggable>
          <el-upload
            class="avatar-uploader"
            :style="{display:isMax?'none':''}"
            action="#"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG"
            :show-file-list="false"
            :http-request="handleUploda"
            :before-upload="beforeAvatarUpload"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-row>
      </el-form-item>
      <el-form-item label="课程名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请填写课程名称" />
      </el-form-item>
      <el-form-item label="课程分类" prop="categoryId" required>
        <el-select v-model="ruleForm.categoryId" placeholder="请选择课程类型">
          <el-option
            v-for="(item,index) in courseCategoryOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="false" label="年级" prop="gradeIds">
        <el-checkbox-group v-model="ruleForm.gradeIds ">
          <el-checkbox
            v-for="item in courseGradeListOptions"
            :key="item.id"
            :label="item.id"
          >{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="课程性质" prop="courseNatureId">
        <el-radio-group v-model="ruleForm.courseNatureId" @change="courseNatureIdChange">
          <el-radio
            v-for="item in courseNatureOptions"
            :key="item.id"
            :label="item.id"
          >{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="适合年级" required>
        <!-- <el-row>
          <el-col>
            <el-radio-group v-model="ruleForm.isAgeLimit">
              <el-radio :label="0">不限制</el-radio>
              <el-radio :label="1">限制年龄</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>-->
        <el-row class="edit-age">
          <el-col :span="5">
            <el-form-item prop="gradeBegin">
              <el-select v-model="ruleForm.gradeBegin" size="mini" placeholder="请选择">
                <el-option
                  v-for="(item,index) in ageOptions"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align:center">
            <span>至</span>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="gradeEnd">
              <el-select v-model="ruleForm.gradeEnd" size="mini" placeholder="请选择">
                <el-option
                  v-for="(item,index) in ageOptions"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="每节时长" label-width="100px" prop="lessonTime">
        <el-select v-model="ruleForm.lessonTime" size="mini" placeholder="请选择">
          <el-option
            v-for="item in lessonTimeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上课老师">
        <el-row type="flex">
          <el-form-item prop="teacherId">
            <el-select
              popper-class="change-teacher"
              v-model="ruleForm.teacherId"
              clearable
              placeholder="选择老师"
              :popper-append-to-body="false"
              @change="changeTeacher"
            >
              <el-option
                v-for="item in teacherData"
                :key="item.value"
                :label="item.realName"
                :value="item.userId"
              >
                <div style="display:flex;justify-content:space-between;align-items:center">
                  <div>{{ item.realName }}</div>
                  <el-image style="width:50px;height:50px" :src="item.avatar"></el-image>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
            class="input-new-tag"
            v-if="addTeacherNameVisible"
            v-model="addTeacherName"
            :minlength="1"
            :maxlength="7"
            size="small"
            @keyup.enter.native="handleInputaddTeacherName"
            @blur="handleInputaddTeacherName"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInputaddTeacherName">+ 添加老师</el-button>
        </el-form-item>
        </el-row>
      </el-form-item>
      <el-form-item v-show="ruleForm.teacherImg" label="老师头像">
        <img style="width:130px;height:130px" :src="ruleForm.teacherImg" alt="无内容" />
      </el-form-item>
      <!-- <el-form-item label="上课老师" prop="teacherName">
        <el-input v-model="ruleForm.teacherName" placeholder="请填写授课老师" />
      </el-form-item>-->
      <el-form-item label="老师简介">
        <el-tag
          :key="index"
          v-for="(tag,index) in ruleForm.teacherProfile"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          :minlength="1"
          :maxlength="7"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加简介</el-button>
      </el-form-item>
      <el-form-item label="购买需知" >
        <el-row class="edit-matter" :gutter="10">
          <el-col :span="2">
            <el-button size="mini" @click="editMatter">编辑</el-button>
          </el-col>
          <!-- <el-col :span="3">
            <el-button size="mini" type="text">自定义模板</el-button>
          </el-col>-->
          <el-col :span="1" class="icon">
            <el-tooltip class="item" effect="dark" :content="tooltipInfo" placement="top-start">
              <i class="el-icon-question" />
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="课程标签" prop="courseLabel">
        <!-- <el-select v-model="ruleForm.courseLabel" class="courseLabel-select" multiple placeholder="请选择课程标签">
          <el-option
            v-for="item in courseLabelListA"
            :key="item.id"
            :label="item.labelName"
            :value="item.id"
          />
        </el-select>-->
        <el-checkbox-group v-model="ruleForm.courseLabel" :min="0" :max="3" size="mini" border>
          <el-checkbox
            v-for="(item,index) in courseLabelListA"
            :label="item.id"
            :key="index"
          >{{item.labelName}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="报名人数初始值" label-width="140px" prop="initialRegistrationCount" required>
        <el-select v-model="ruleForm.initialRegistrationCount" placeholder="请选择">
          <el-option
            v-for="item in peopleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否应用到其它分校" label-width="164px" prop="isApplyBranchSchool" required>
        <el-row>
          <el-col>
            <el-radio-group v-model="ruleForm.isApplyBranchSchool">
              <el-radio :label="0">不应用</el-radio>
              <el-radio :label="1">应用</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row v-show="ruleForm.isApplyBranchSchool===1">
          <el-col>
            <el-checkbox-group v-model="ruleForm.branchSchoolIds ">
              <el-checkbox
                v-for="item in schoolOption"
                :key="item.id"
                :label="item.id"
              >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="课程概况" prop="overview">
        <el-input
          v-model="ruleForm.overview"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 6}"
          :maxlength="150"
          show-word-limit
          placeholder="请简要介绍您的课程"
        />
      </el-form-item>

      <el-form-item label="课程特色" prop="feature">
        <el-input
          v-model="ruleForm.feature"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 6}"
          :maxlength="150"
          show-word-limit
          placeholder="请介绍一下您的课程特色"
        />
      </el-form-item>

      <el-form-item label="课程详情" prop="details">
        <tinymce v-model="ruleForm.details" :height="500" />
      </el-form-item>
      <el-form-item label="课程套餐" prop="courseSetMeals">
        <el-table
          :data="ruleForm.courseSetMeals"
          :border="true"
          :header-cell-style="{background:global.mainColor}"
          style="width: 100%"
        >
          <el-table-column prop="name" label="套餐名称" align="center" />
          <el-table-column prop="price" label="价格" align="center" />
          <!-- <el-table-column prop="lessonTime" label="课时" align="center" /> -->
          <el-table-column prop="classTime" label="上课时间" align="center" />
          <el-table-column prop="teachingMethods" label="授课方式" align="center" />
          <el-table-column prop="address" label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="addPackage">新增套餐</el-button>
      </el-form-item>
      <el-form-item v-if="!$route.query.view">
        <el-row type="flex" justify="center">
          <el-button
            type="primary"
            :loading="reLeaseLoading"
            @click="reLeaseCourse('ruleForm')"
          >发布课程</el-button>
          <el-button :loading="addDraftLoading" @click="addDraft('ruleForm')">保存草稿</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-row>
      </el-form-item>
    </el-form>
    <!-- 购买需知弹窗 -->
    <el-dialog
      title="购买需知"
      :visible.sync="dialogMatterVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @open="dialogMatterOpen"
      width="600px"
    >
      <el-row type="flex" justify="center">
        <p style="color:red">
          尊敬的买家朋友，请在本平台购买产品之前，一定要花几分钟认真阅读以下内容
          以避免我们的交易发生一些不必要的误会。
        </p>
      </el-row>
      <div class="matter-box">
        <el-radio-group style="margin-left:20px" v-model="activeName">
          <el-radio label="first">协议模板一</el-radio>
          <el-radio label="second">协议模板二</el-radio>
          <el-radio label="third">自定义模板</el-radio>
        </el-radio-group>
        <div v-if="activeName==='first'">
          <el-row type="flex" justify="center">
            <h3>购买须知</h3>
          </el-row>
          <div class="matter">
            <p>有效期</p>
            <p>从客户成功购买课程之时开始起算，到课程完结之时服务结束</p>
          </div>
          <div class="matter">
            <p>上课时间</p>
            <p>{{purchaseInfo.schoolTime}}</p>
          </div>
          <div class="matter">
            <p>适用人数</p>
            <p>{{purchaseInfo.userCount}}</p>
          </div>
          <div class="matter">
            <p>商家服务</p>
            <p>{{purchaseInfo.services}}</p>
          </div>
          <div class="matter">
            <p>温馨提示</p>
            <p style="line-height:20px">
              （1）产品相关信息（包括但不限于产品图片、产品价格、产品质量等）由商家自行提供，产品以实物为准。信息内容的真实性、准确性和合法性由相关商家负责，本平台对此不承担任何保证责任。
              <br />（2）同一账号如需在同一店铺里，单次重复购买同一商品，请分开下单。
              <br />（3）发票开具和邮寄事项细节请联系商家确认。
              <br />（4）买家如对售后服务，包括但不限于发货时间、物流配送、退换服务等有疑问的，请与商家联系确认。
              <br />（5）如有任何问题，欢迎随时与我们的客服联系。
              <br />
            </p>
            <!-- <p>{{purchaseInfo.ts2}}</p>
            <p>{{purchaseInfo.ts3}}</p>

            <p>{{purchaseInfo.ts4}}</p>
            <p>{{purchaseInfo.ts5}}</p>-->
          </div>
          <div class="matter">
            <p>退款说明：</p>
            <el-input
              style="width:100%"
              v-model="purchaseInfo.refundNote"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请填写关于退款的相关说明，如：自购买课程起X天内可退款"
            ></el-input>
          </div>
        </div>
        <div v-if="activeName==='second'">
          <el-row type="flex" justify="center">
            <h3>购买须知</h3>
          </el-row>
          <div class="matter">
            <p>有效期</p>
            <p>从客户成功购买课程之时开始起算，到课程完结之时服务结束</p>
          </div>
          <div class="matter">
            <p>上课时间</p>
            <p>{{purchaseInfo2.schoolTime}}</p>
          </div>
          <div class="matter">
            <p>适用人数</p>
            <p>{{purchaseInfo2.userCount}}</p>
          </div>
          <div class="matter">
            <p>商家服务</p>
            <p>{{purchaseInfo2.services}}</p>
          </div>
          <div class="matter">
            <p>温馨提示</p>
           <p style="line-height:20px">
              （1）产品相关信息（包括但不限于产品图片、产品价格、产品质量等）由商家自行提供，产品以实物为准。信息内容的真实性、准确性和合法性由相关商家负责，本平台对此不承担任何保证责任。
              <br />（2）同一账号如需在同一店铺里，单次重复购买同一商品，请分开下单。
              <br />（3）发票开具和邮寄事项细节请联系商家确认。
              <br />（4）买家如对售后服务，包括但不限于发货时间、物流配送、退换服务等有疑问的，请与商家联系确认。
              <br />（5）如有任何问题，欢迎随时与我们的客服联系。
              <br />
            </p>
          </div>
          <div class="matter">
            <p>退款说明：</p>
            <el-input
              style="width:100%"
              v-model="purchaseInfo2.refundNote"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请填写关于退款的相关说明，如：自购买课程起X天内可退款"
            ></el-input>
          </div>
        </div>
        <div v-if="activeName==='third'">
          <el-row type="flex" justify="center">
            <h3>购买须知</h3>
          </el-row>
          <div class="matter">
            <p>有效期</p>
            <p>从客户成功购买课程之时开始起算，到课程完结之时服务结束</p>
          </div>
          <el-form ref="matterFrom" :model="matterFrom" :rules="matterRules">
            <el-form-item label="上课时间" label-width="80px" prop="schoolTime">
              <el-input v-model="matterFrom.schoolTime" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适用人数" label-width="80px" prop="userCount">
              <el-input v-model="matterFrom.userCount" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商家服务" label-width="80px" prop="services">
              <el-input v-model="matterFrom.services" autocomplete="off" />
            </el-form-item>
            <el-form-item label="温馨提示" label-width="80px" prop="tips">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 6}"
                v-model="matterFrom.tips"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="退款说明" label-width="80px" prop="refundNote">
              <el-input
                style="width:100%"
                v-model="matterFrom.refundNote"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请填写关于退款的相关说明，如：自购买课程起X天内可退款"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="resetMatterFrom">取 消</el-button>
        <el-button size="small" type="primary" @click="matterFromSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增套餐弹窗 -->
    <addCourseDialog
      :visible.sync="dialogFormVisible"
      :courseSetMealsData="ruleForm.courseSetMeals"
      :is-add="isAdd"
      :isExperience="isExperience"
      :course-set-meals-form.sync="courseSetMealsForm"
      @confirm="confirmAddPackage"
    />
    <!-- 图片裁剪 -->
    <el-dialog
      title="裁剪图片"
      :visible.sync="cropper.dialog"
      width="800px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <VueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :centerBox="option.centerBox"
            :infoTrue="option.infoTrue"
            :fixedBox="option.fixedBox"
            @realTime="realTime"
          ></VueCropper>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cropper.dialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import imageCropper from '@/components/ImageCropper'
import { VueCropper } from 'vue-cropper'
import draggable from 'vuedraggable'
import tinymce from '@/components/Tinymce'
import addCourseDialog from '@/views/curriculum/compoents/addCourseDialog'
import { deepClone } from '@/utils'
import { getGrade } from '@/api/common'
import {
  businessList,
  courseNatureList,
  courseCategoryList,
  courseLabelList,
  getTeachers,
  getBoById,
  updateCourse
} from '@/api/curriculum'
export default {
  name: 'EditCourse',
  components: {
    // imageCropper,
    VueCropper,
    draggable,
    tinymce,
    addCourseDialog
  },
  data() {
    var validateGradeEnd = (rule, value, callback) => {
      if (value < this.ruleForm.gradeBegin) {
        return callback(new Error('最大年级范围不能小于最小年级范围'))
      } else {
        callback()
      }
    }
    return {
      reLeaseLoading: false,
      addDraftLoading: false,
      imgKey: 0,
      imgList: [
        // 图片列表
        {
          url: '/'
        }
      ],
      // 裁剪组件的基础配置option
      option: {
        mode: 'cover', // 图片默认渲染方式
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 100, // 默认生成截图框宽度
        autoCropHeight: 100, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [750, 560], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      cropper: {
        dialog: false,
        src: '',
        width: 750,
        height: 560,
        aspectRatio: 750 / 560,
        fileBlob: {}
      },
      purchaseInfo: {
        // 购买需知默认
        schoolTime: '具体时间以机构实际排课时间为准',
        userCount: '每张订单最多1人使用，不能转让他人使用',
        services: '提供停车位,免费WIFI',
        tips:
          '（1）产品相关信息（包括但不限于产品图片、产品价格、产品质量等）由商家自行提供，产品以实物为准。信息内容的真实性、准确性和合法性由相关商家负责，本平台对此不承担任何保证责任。（2）同一账号如需在同一店铺里，单次重复购买同一商品，请分开下单。（3）发票开具和邮寄事项细节请联系商家确认。（4）买家如对售后服务，包括但不限于发货时间、物流配送、退换服务等有疑问的，请与商家联系确认。（5）如有任何问题，欢迎随时与我们的客服联系。',
        refundNote: ''
      },
      purchaseInfo2: {
        // 购买需知默认
        schoolTime: '具体时间以机构实际排课时间为准',
        userCount: '每张订单最多1人使用，不能转让他人使用',
        services: '免费WIFI',
        tips:
          '（1）产品相关信息（包括但不限于产品图片、产品价格、产品质量等）由商家自行提供，产品以实物为准。信息内容的真实性、准确性和合法性由相关商家负责，本平台对此不承担任何保证责任。（2）同一账号如需在同一店铺里，单次重复购买同一商品，请分开下单。（3）发票开具和邮寄事项细节请联系商家确认。（4）买家如对售后服务，包括但不限于发货时间、物流配送、退换服务等有疑问的，请与商家联系确认。（5）如有任何问题，欢迎随时与我们的客服联系。',
        refundNote: ''
      },
      teacherData: [],
      cropperShow: false, // 是否显示图片裁剪
      isMax: false, // 图片超出5个隐藏
      // fileList: [], // 图片列表
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: true,
      dialogMatterVisible: false, // 购买需知弹窗
      activeName: 'first', // 购买需知tabs
      matterFrom: {
        // 购买需知表单数据
        schoolTime: '',
        userCount: '',
        services: '',
        tips: '',
        refundNote: ''
      },
      matterRules: {
        // 购买需知表单校验
        schoolTime: [
          { required: true, message: '请输入上课时间', trigger: 'blur' }
        ],
        userCount: [
          { required: true, message: '请输入适用人数', trigger: 'blur' }
        ],
        services: [
          { required: true, message: '请输入商家服务', trigger: 'blur' }
        ],
        tips: [{ required: true, message: '请输入温馨提示', trigger: 'blur' }],
        refundNote: [
          { required: true, message: '请输入退款说明', trigger: 'blur' }
        ]
      },
      dialogFormVisible: false, // 新增套餐dialog
      isAdd: false,
      isEdit: false, // 是否编辑套餐
      isExperience: false, // 是否体验课
      courseSetMealsForm: {}, // 编辑套餐数据
      courseGradeListOptions: [], // 年级集合
      courseNatureOptions: [], // 课程性质
      courseCategoryOptions: [], // 课程分类
      courseLabelListA: [{}], // 课程标签
      tooltipInfo:
        '购买须知是为了避免课程售后纠纷，提高沟通效率，降低风险，请认真填写本须知',
      // 年龄范围
      ageOptions: [],
      // 分校
      schoolOption: [],
      // 报名人数初始值
      peopleOptions: [
        {
          lable: '0',
          value: 0
        },
        {
          lable: '1',
          value: 1
        },
        {
          lable: '2',
          value: 2
        },
        {
          lable: '3',
          value: 3
        },
        {
          lable: '4',
          value: 4
        },
        {
          lable: '5',
          value: 5
        }
      ],
      // 每节时长
      lessonTimeOptions: [
        {
          label: '30分钟',
          value: 30
        },
        {
          label: '40分钟',
          value: 40
        },
        {
          label: '45分钟',
          value: 45
        },
        {
          label: '1小时',
          value: 60
        },
        {
          label: '1小时30分钟',
          value: 90
        },
        {
          label: '2小时',
          value: 120
        },
        {
          label: '2小时30分钟',
          value: 150
        },
        {
          label: '3小时',
          value: 180
        }
      ],
      inputVisible: false,
      inputValue: '',
      addTeacherNameVisible: false,
      addTeacherName: '', // 添加老师
      ruleForm: {
        imgUpload: '',
        introducePictures: [],
        name: '', // 课程名称
        // gradeIds: [],
        isAgeLimit: 0, // 是否限制年龄 1限制 0不限制
        gradeBegin: 1, // 最小年龄
        gradeEnd: 2, // 最大年龄
        categoryId: null, // 课程分类
        courseNatureId: '0', // 课程性质
        teacherId: '', // 老师id
        teacherName: '', // 上课老师
        teacherProfile: [],
        teacherProfile1: '', // 老师简介
        teacherProfile2: '',
        teacherProfile3: '',
        courseProtocolTemplate: {
          // 购买需知表单数据
          schoolTime: '',
          userCount: '',
          services: '',
          tips: '',
          refundNote: ''
        },
        courseLabel: [], // 课程标签
        // 报名人数
        initialRegistrationCount: 3,
        isApplyBranchSchool: 0, // 是否应用到其它分校
        branchSchoolIds: [], // 其它分校id
        lessonTime: null, // 每节时长
        // 课程概况
        overview: '',
        // 课程特色
        courseHighlights: '',
        // 课程详情
        details: '',
        // 课程套餐
        courseSetMeals: [],
        teacherImg: ''
      },
      rules: {
        introducePictures: [
          {
            type: 'array',
            required: true,
            message: '请上传课程相册',
            trigger: 'change'
          }
        ],
        name: [
          { required: true, message: '请输入课程名称', trigger: 'change' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: 'change'
          }
        ],
        categoryId: [
          { required: true, message: '请选择课程分类', trigger: 'change' }
        ],
        gradeIds: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        courseNatureId: [
          { required: true, message: '请选择课程性质', trigger: 'change' }
        ],
        gradeBegin: [
          { required: true, message: '请选择年级范围', trigger: 'change' }
        ],
        gradeEnd: [
          { required: true, message: '请选择年级范围', trigger: 'blur' },
          { validator: validateGradeEnd, trigger: 'change' }
        ],
        lessonTime: [
          { required: true, message: '请选择每节时长', trigger: 'change' }
        ],
        teacherName: [
          { required: true, message: '请选择时长', trigger: 'change' }
        ],
        teacherProfile1: [
          { message: '请填写简介', trigger: 'blur' },
          {
            min: 0,
            max: 7,
            message: '长度在 0 到 7 个字符',
            trigger: 'change'
          }
        ],
        teacherProfile2: [
          { message: '请填写简介', trigger: 'blur' },
          {
            min: 0,
            max: 7,
            message: '长度在 0 到 7 个字符',
            trigger: 'change'
          }
        ],
        teacherProfile3: [
          { message: '请填写简介', trigger: 'blur' },
          {
            min: 0,
            max: 7,
            message: '长度在 0 到 7 个字符',
            trigger: 'change'
          }
        ],
        courseProtocolTemplate: [
          { required: true, message: '请填写购买需知', trigger: 'blur' }
        ],
        'courseProtocolTemplate.refundNote': [
          { required: true, message: '请完整填写购买需知', trigger: 'blur' }
        ],
        courseLabel: [
          {
            type: 'array',
            required: true,
            message: '请选择至少一项最多三项',
            trigger: 'change'
          }
        ],
        isApplyBranchSchool: [
          { required: true, message: '请选择一项', trigger: 'change' }
        ],
        overview: [
          { required: true, message: '请填写课程概况', trigger: 'blur' }
        ],
        feature: [
          { required: true, message: '请输入课程特色', trigger: 'blur' },
          {
            min: 0,
            max: 150,
            message: '长度在 0 到 150 个字符',
            trigger: 'change'
          }
        ],
        details: [
          { required: true, message: '请输入课程详情', trigger: 'change' }
        ],
        courseSetMeals: [
          {
            type: 'array',
            required: true,
            message: '请填写套餐',
            trigger: 'change'
          }
        ],
        date1: [{ required: true, message: '请选择课程', trigger: 'change' }],
        type: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {
    'ruleForm.introducePictures'(v) {
      this.isMax = v.length >= 5
    },
    activeName(val) {
      if (val === 'third') {
        this.matterFrom = this.ruleForm.courseProtocolTemplate
      }
    },
    // 'ruleForm.courseNatureId'(v) {
    //   this.isExperience =
    //     this.courseNatureOptions.find(i => i.id === v).name === '体验课'
    // },
    'ruleForm.isApplyBranchSchool'(v) {
      // 是否应用到分校
      if (v === 0) {
        this.ruleForm.branchSchoolIds = []
      } else {
        // 查询分校
        businessList({
          parentId: this.$store.getters.businessId,
          status: 2,
          isCertified: 1
        })
          .then(res => {
            res.data.forEach(i => {
              i.id = String(i.id)
            })
            this.schoolOption = res.data
          })
          .catch(() => {})
      }
    }
  },
  created() {
    this.getCourseList()
  },
  methods: {
    handleUpload() {
      this.cropperShow = true

      this.imgList.push({
        url: '/'
      })
    },
    // 删除相册图片
    removeImg(index) {
      this.ruleForm.introducePictures.splice(index, 1)
    },
    // 图片裁剪插件
    cropperClose() {
      this.cropperShow = false
    },
    // 将 base64转换为 blob 上传oss
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    handleUploda(res, fileList) {
      this.isLogoImg = false
      console.log(res, fileList, 'res, file)')
      this.cropper = {
        dialog: true,
        src: '',
        width: 750,
        height: 560,
        aspectRatio: 375 / 280
      }
      // this.cropper.src = URL.createObjectURL(res.file)
      this.option.img = URL.createObjectURL(res.file)
    },
    confirmCropper() {
      this.$refs.cropper.getCropBlob(data => {
        // var fileName = 'goods' + this.fileinfo.uid
        console.log(data, 'dddss')
        const raw = {
          raw: data,
          name: new Date().valueOf()
        }
        this.uploadImgToOss(raw)
          .then(response => {
            const { imgUrl } = response
            this.ruleForm.introducePictures.push(imgUrl)
          })
          .finally(() => {
            this.cropper.dialog = false
          })
      })
    },
    // 裁剪后上传
    fileBlob(blod) {
      const raw = {
        raw: blod,
        name: new Date().valueOf()
      }
      this.uploadImgToOss(raw)
        .then(response => {
          const { imgUrl } = response
          this.ruleForm.introducePictures.push(imgUrl)
        })
        .finally(() => {
          this.cropper.dialog = false
        })
    },
    realTime(val) {
      // console.log(val, ';shang')
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size < 1024 * 1024 * 5
      // const isSize = new Promise(function(resolve, reject) {
      //   const width = 750 // 限制图片尺寸为654X270
      //   const height = 560
      //   const _URL = window.URL || window.webkitURL
      //   const img = new Image()
      //   img.onload = function() {
      //     const valid = img.width > width && img.height > height
      //     valid ? resolve() : reject()
      //   }
      //   img.src = _URL.createObjectURL(file)
      // }).then(() => {
      //   return file
      // }, () => {
      //   this.$message.error('图片大小不可超过5MB')
      //   return Promise.reject()
      // })
      if (!isLt2M) {
        this.$message.error('图片大小不可超过5MB')
      }
      return isLt2M
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleTagClose(tag) {
      this.coureTag.splice(this.coureTag.indexOf(tag), 1)
    },
    courseNatureIdChange(val) {
      this.isExperience =
        this.courseNatureOptions.find(i => i.id === val).name === '体验课'
    },
    showInputaddTeacherName() {
      this.addTeacherNameVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputaddTeacherName() {
      const inputValue = this.addTeacherName
      if (inputValue) {
        if (this.teacherData[0].userId === '') {
          this.teacherData.splice(0, 1, {
            realName: inputValue,
            userId: ''
          })
        } else {
          this.teacherData.splice(0, 0, {
            realName: inputValue,
            userId: ''
          })
        }
      }
      this.ruleForm.teacherId = ''
      this.addTeacherNameVisible = false
      this.addTeacherName = ''
    },
    // 选择老师
    changeTeacher(val) {
      console.log(val, event, ';;;;sfsd')
      if (val) {
        let obj = {}
        obj = this.teacherData.find(i => i.userId === val)
        this.ruleForm.teacherName = obj ? obj.realName : ''
        this.ruleForm.teacherImg = obj ? obj.avatar : ''
      } else {
        this.ruleForm.teacherId = ''
        this.ruleForm.teacherName = ''
        this.ruleForm.teacherImg = ''
        // this.ruleForm.teacherProfile1 = ''
        // this.ruleForm.teacherProfile2 = ''
        // this.ruleForm.teacherProfile3 = ''
      }
    },
    handleClose(tag) {
      this.ruleForm.teacherProfile.splice(this.ruleForm.teacherProfile.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.ruleForm.teacherProfile.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 购买需知
    editMatter() {
      // this.matterFrom = this.ruleForm.courseProtocolTemplate
      this.dialogMatterVisible = true
    },
    // 清除购买需知表单
    resetMatterFrom() {
      this.dialogMatterVisible = false
      // this.$refs.matterFrom.resetFields()
    },
    dialogMatterOpen() {
      // this.matterFrom.tips = this.purchaseInfo.tips
      // this.matterFrom = this.purchaseInfo
    },
    // 购买需知确定
    matterFromSubmit() {
      if (this.activeName === 'third') {
        this.$refs.matterFrom.validate(valid => {
          if (valid) {
            this.matterFrom = this.ruleForm.courseProtocolTemplate
            // this.ruleForm.courseProtocolTemplate = this.matterFrom
            this.dialogMatterVisible = false
          } else {
            return false
          }
        })
      } else {
        if (this.activeName === 'first') {
          if (this.purchaseInfo.refundNote) {
            // this.matterFrom.tips = this.purchaseInfo.tips
            this.ruleForm.courseProtocolTemplate = this.purchaseInfo
            this.dialogMatterVisible = false
          } else {
            this.$message.error('请填写退款说明')
          }
        }
        if (this.activeName === 'second') {
          if (this.purchaseInfo2.refundNote) {
            // this.matterFrom.tips = this.purchaseInfo2.tips
            this.ruleForm.courseProtocolTemplate = this.purchaseInfo2
            this.dialogMatterVisible = false
          } else {
            this.$message.error('请填写退款说明')
          }
        }
      }
    },
    // 编辑
    handleEdit(index, row) {
      this.isEdit = true
      this.courseSetMealsForm = row
      this.dialogFormVisible = true
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('此操作将删除该套餐, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.ruleForm.courseSetMeals.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增套餐
    addPackage() {
      this.dialogFormVisible = true
      this.isAdd = true
      this.isEdit = false
      this.courseSetMealsForm = {}
    },
    // 确定新增套餐
    confirmAddPackage(data) {
      if (!this.isEdit) {
        this.ruleForm.courseSetMeals.push({
          ...data,
          date: new Date().valueOf(),
          isAdd: true
        })
      }
    },
    // 发布课程
    async setReLeaseCourse() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // const data = Object.assign({}, this.ruleForm)
          const data = deepClone(this.ruleForm)
          data.teacherProfile = `${data.teacherProfile1 &&
            data.teacherProfile1},${data.teacherProfile2 &&
            data.teacherProfile2},${data.teacherProfile3 &&
            data.teacherProfile3}`
          data.courseProtocolTemplate = this.matterFrom
          data.courseSetMeals = data.courseSetMeals.map(i => {
            if (i.isAdd) {
              delete i.id
              return i
            } else {
              return i
            }
          })
          const labelObj = this.courseLabelListA.filter(i => {
            return i.id === data.courseLabel.indexOf(i.id) !== -1
          })
          data.labelName = labelObj.map(i => {
            return i.labelName
          })
          const categoryName = this.courseCategoryOptions.find(
            i => i.id === data.categoryId
          ).name
          data.categoryName = categoryName
          this.$emit('release', data)
          // this.$refs.ruleForm.resetFields()
        } else {
          this.$message({
            message: '请完善课程信息',
            type: 'error'
          })
          return false
        }
      })
    },
    // 发布课程
    reLeaseCourse() {
      this.fnThrottle(this.setReLeaseCourse, 1000, 1000)()
    },
    // 保存草稿
    setDraft() {
      this.$refs.ruleForm.clearValidate()
      this.addDraftLoading = true
      this.$emit('addDraft', this.ruleForm)
      // this.$refs.ruleForm.resetFields()
      this.addDraftLoading = false
    },
    resetForm(formName) {
      this.$confirm('您的信息将不会被保存，确定取消吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // this.$refs[formName].resetFields()
          const tagsAll = this.$store.state.tagsView.visitedViews
          const tag = tagsAll.find(i => i.path === '/curriculum/edit')
          const tagadd = tagsAll.find(i => i.path === '/curriculum/add')
          this.$store
            .dispatch('tagsView/delView', tag || tagadd)
            .then(({ visitedViews }) => {
              this.$router.replace({ path: '/redirect/curriculum' })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 保存草稿
    addDraft() {
      this.fnThrottle(this.setDraft, 1000, 1000)()
    },
    getCourseList() {
      // 获取单个课程
      getBoById({
        id: this.$route.query.id || '1286146601954250754'
      }).then(res => {
        console.log(res, 'res')

        const teacherRem = res.data.teacherProfile ? res.data.teacherProfile.split(',') : []
        const data = res.data
        this.status = data.status
        this.ruleForm = data
        this.ruleForm.teacherProfile = teacherRem
        this.ruleForm.teacherProfile1 = teacherRem[0] || ''
        this.ruleForm.teacherProfile2 = teacherRem[1] || ''
        this.ruleForm.teacherProfile3 = teacherRem[2] || ''
        // 课程标签转换数组
        const arr = this.ruleForm.courseLabel ? this.ruleForm.courseLabel.split(',') : []
        const branchSchoolIds = this.ruleForm.branchSchoolIds ? this.ruleForm.branchSchoolIds.split(',') : []
        const introducePictures = this.ruleForm.introducePictures ? this.ruleForm.introducePictures.split(',') : []
        this.$set(this.ruleForm, 'courseLabel', arr)
        this.$set(this.ruleForm, 'branchSchoolIds', branchSchoolIds)
        this.$set(this.ruleForm, 'introducePictures', introducePictures)
        console.log(this.ruleForm, 'this.ruleForm')
      }).catch(() => {})
      // 适合年级
      getGrade().then(res => {
        const data = res.data
        data.forEach(i => {
          i.gradeList.forEach(j => {
            this.ageOptions.push(j)
          })
        })
      })
      // 获取老师集合
      getTeachers({
        businessId: this.$store.getters.businessId
      }).then(res => {
        this.teacherData = res.data || []
      })
      // 课程性质列表
      courseNatureList({
        currentPage: 1,
        pageSize: 10
      })
        .then(res => {
          // this.courseNatureOptions = res.data.records
          // if (res.data.records.length <= 0) return
          res.data.records.forEach(i => {
            i.id = String(i.id)
          })
          this.courseNatureOptions = res.data.records
        })
        .catch(() => {})

      // 分类列表
      courseCategoryList({
        id: this.$store.getters.businessId
      })
        .then(res => {
          this.courseCategoryOptions = res.data
        })
        .catch(() => {})

      // 获取课程标签
      courseLabelList({}).then(res => {
        const { data } = res
        // if (data.length <= 0) return
        data.forEach(i => {
          i.id = String(i.id)
        })
        this.$nextTick(() => {
          this.courseLabelListA = data
        })
      })
    },
    // 节流
    fnThrottle(method, delay, duration) {
      var that = this
      var timer = this.timer
      var begin = new Date().getTime()
      return function() {
        var context = that
        var args = arguments
        var current = new Date().getTime()
        clearTimeout(timer)
        if (current - begin >= duration) {
          method.apply(context, args)
          begin = current
        } else {
          console.log(delay)
          that.timer = setTimeout(function() {
            method.apply(context, args)
          }, delay)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.matter {
  margin-bottom: 15px;
  p {
    margin: 5px 0;
    &:first-child {
      font-size: 14px;
      font-weight: 600;
    }
    /deep/.el-textarea__inner {
      width: 100%;
    }
  }
}
.edit-box {
  width: 100%;
  .img-upload {
    cursor: pointer;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 5px;
    width: 187.5px;
    height: 140px;
    border: 1px dashed #6bb6fc;
    border-radius: 5px;
    i {
      font-size: 24px;
      color: #6bb6fc;
    }
    .el-image {
      cursor: pointer;
      width: 100%;
      height: 100%;
    }
    &:hover .img-upload-shaow {
      display: flex;
    }
    .img-upload-shaow {
      display: none;
      // display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      background: rgba(0, 0, 0, 0.3);
      // opacity: 0;
      > i {
        color: #fff;
      }
    }
  }
}
.courseLabel-select {
  width: 350px;
}
.avatar-uploader {
  /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    border: 1px dashed #409eff;
  }
  /deep/.avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 135px;
    height: 135px;
    line-height: 135px;
    text-align: center;
  }
  /deep/.avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
}
/deep/.el-upload--picture-card,
/deep/.el-upload-list__item {
  width: 125px;
  height: 94px;
  line-height: 94px;
}
.disabled /deep/.avatar-uploader {
  display: none;
}
.el-input,
/deep/.el-textarea__inner {
  width: 400px;
}
.teacher {
  margin-bottom: 20px;
}
.edit-matter {
  width: 700px;
}
.edit-age {
  width: 700px;
}
.icon {
  color: rgb(167, 167, 167);
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 150px;
  margin-left: 10px;
  vertical-align: bottom;
}
.markdown {
  width: 100%;
}
/deep/.tui-editor .te-preview-style-vertical .te-preview {
  width: 100%;
}
/deep/.te-md-splitter {
  width: 50%;
}
/deep/.change-teacher .el-select-dropdown__item {
  height: 60px !important;
  line-height: 60px !important;
}
.matter-box {
  padding: 20px;
  box-shadow: 1px 1px 5px #eee;
}
// 截图
.cropper-content {
  .cropper {
    width: 750px;
    height: 560px;
  }
}
</style>
